package com.app.util;

import com.itextpdf.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
public final class HtmlUtil {
    private HtmlUtil() {
    }
    // 字体路径，放在资源目录下
    private static final String FONT_PATH = "C:/91885/simsun.ttc";

    public static void file2Pdf(File htmlFile, String pdfFile){
        try (OutputStream os = new FileOutputStream(pdfFile)) {
            String url = htmlFile.toURI().toURL().toString();
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            // 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            // 获取字体绝对路径，ApplicationContextUtil是我自己写的类
            String fontPath = ResourceUtils.getURL(FONT_PATH).getPath();
            fontResolver.addFont(FONT_PATH, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            // 抛出自定义异常

        }
    }
    public static void html2Pdf(String html, String pdfFile) {
        String pdfDir = StringUtils.substringBeforeLast(pdfFile, "/");
        File file = new File(pdfDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (OutputStream os = new FileOutputStream(pdfFile)) {
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html);
            // 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            // 获取字体绝对路径，ApplicationContextUtil是我自己写的类
            String fontPath = ResourceUtils.getURL(FONT_PATH).getPath();
            fontResolver.addFont(FONT_PATH, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

//    public static void main(String[] args) throws FileNotFoundException {
//        String path = ResourceUtils.getURL("classpath:templates/simsun.ttc").getPath();
//        System.out.println(path);
//    }
}
